package com.LeeCode;

/**
 * 二叉树的坡度
 */

public class Code563 {
    public static void main(String[] args) {
        Integer[] arr = {4, 2, 9, 3, 5, null, 7};
        TreeNode root = Utils.buildTree(arr);
        System.out.println(new Code563().findTilt(root));
    }

    private int sum = 0;

    public int findTilt(TreeNode root) {
        dfs(root);
        return sum;
    }

    private int dfs(TreeNode root) {
        if (root == null) return 0;
        int left = dfs(root.left);
        int right = dfs(root.right);
        sum += Math.abs(left - right);
        return left + right + root.val;
    }
}
